package com.beiding.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import feign.RequestInterceptor;
import feign.Response;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.codec.ErrorDecoder;
import io.undertow.util.BadRequestException;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Enumeration;

@Configuration
public class CommonFeignConfig {


    @Bean
    public ErrorDecoder errorDecoder() {

        return new ErrorDecoder() {

            ObjectMapper mapper = new ObjectMapper();

            @Override
            public Exception decode(String methodKey, Response response) {

                String body = "";

                try {


                    Reader reader = response.body().asReader();

                    BufferedReader r = new BufferedReader(reader);

                    String line = "";

                    while ((line = r.readLine()) != null) {
                        body += line;
                    }

                } catch (IOException ignore) {

                }

                return new FeignErrorException(response.status(), body);
            }

        };

    }

    @Bean
    public Encoder springEncoder(ObjectFactory<HttpMessageConverters> messageConverters) {
        return new SpringEncoder(messageConverters);
    }

    @Bean
    public Decoder springDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
        return new SpringDecoder(messageConverters);
    }

    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {


            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

            if (requestAttributes == null) {
                return;
            }

            HttpServletRequest request = requestAttributes.getRequest();

            Enumeration headerNames = request.getHeaderNames();


            /*

                如果被调用的服务使用Security要求调用者提供Cookie,而调用者没有提供Cookie,那么服务会响应404


             */

            while (headerNames.hasMoreElements()) {

                //复制请求头.特别是cookie
                String name = (String) headerNames.nextElement();
                requestTemplate.header(name, request.getHeader(name));
            }

        };
    }


}
